package com.by_man.presenter.module_bluetooth;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.by_man.presenter.R;
import com.by_man.presenter.SharedApplication;
import com.by_man.presenter.module_health_management.measure_blood_pressure.MeasureBloodPressureActivity;
import com.by_man.repository.IpAddress;
import com.by_man.repository.LocalDataManager;
import com.by_man.repository.PostStringRequest;
import com.by_man.repository.UserInfos;
import com.google.gson.Gson;
import com.omron.HEM7081IT.BPDataManager;
import com.omron.HEM7081IT.BPManager;
import com.omron.HEM7081IT.IOmronBaseResponseCallback;
import com.omron.HEM7081IT.IOmronGetDataResultCallback;
import com.omron.HEM7081IT.OmronDataRawBloodPressureData;
import com.omron.HEM7081IT.OmronVariableHealthDataType;


import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//import com.example.OmronHuaweiDevicePlugIn.R;

public class OmronHem extends ActionBarActivity implements View.OnClickListener,
        IOmronBaseResponseCallback, IOmronGetDataResultCallback {
    private RequestQueue rQueue;

    private Button button1;
    private Button button2;
    private Button button3;
    private Toolbar mToolbar;
    private Handler mHandler;
    private TextView mData_systolic,mData_diastolic,mData_pulse;
    private BPManager oMRONDeviceManager = null;
    private BPDataManager oMRONHealthDataManager = null;
    private String TAG = "GestureLockActivity";
    private ListView mlistview;
    private List<Map<String, Object>> testlist = new ArrayList<Map<String, Object>>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_omron);
        rQueue = LocalDataManager.getRequestQueue();
        // 初始化控件
        initView();
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                Intent intent = new Intent(this, MeasureBloodPressureActivity.class);
                startActivity(intent);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(this, MeasureBloodPressureActivity.class);
            startActivity(intent);
        }
        return super.onKeyDown(keyCode,event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button1:
                oMRONDeviceManager.startBinding(this);
                break;

            case R.id.button2:
                oMRONDeviceManager.stopBinding();
                break;

            case R.id.button3:
                oMRONHealthDataManager.getHealthData(this);
                break;
            default:
                break;
        }
    }

    @Override
    public void onFailure(int arg0, String arg1) {
        poastToast(arg1);
        Log.v(TAG, "onFailure " + arg0 + " : " + arg1);
    }

    @Override
    public void onSuccess(HashMap<Integer, ArrayList<Object>> arg0) {
        if (arg0 != null) {


            final ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();


            ArrayList<Object> rawBPDataList = arg0.get(OmronVariableHealthDataType.BLOOD_PRESSURE_DATA);
            for (int i = 0; i < rawBPDataList.size(); i++) {
                final OmronDataRawBloodPressureData bp = (OmronDataRawBloodPressureData) rawBPDataList
                        .get(i);

                long timeM = bp.getStart_time();
                final String data1 = ""+bp.getDiastolic() ;
                final String data2 = "" + bp.getSystolic() ;
                final String data3 = "" +bp.getPulse();
                Date date = new Date();
                date.setTime(bp.getStart_time());
                SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String star_time = sdf.format(date);


                HashMap<String, Object> map = new HashMap<String, Object>();


                map.put("diastolic", data1);

                Map<String, Object> test1 = new HashMap<String, Object>();
                test1.put("id", 2);
                test1.put("type",1);
                test1.put("value", data1);
                test1.put("time", star_time);
                testlist.add(test1);


                map.put("systolis", data2);

                Map<String, Object> test2 = new HashMap<String, Object>();
                test2.put("id", 1);
                test2.put("type",1);
                test2.put("value", data2);
                test2.put("time", star_time);
                testlist.add(test2);


                map.put("pulse", data3);

                Map<String, Object> test4 = new HashMap<String, Object>();
                test4.put("id", 4);
                test4.put("type",1);
                test4.put("value", data3);
                test4.put("time", star_time);
                testlist.add(test4);



                map.put("time", star_time);



                listItem.add(map);

            }
            SimpleAdapter adapter;
            adapter = new SimpleAdapter(OmronHem.this, listItem, R.layout.list_omron, new String[]{"systolis", "diastolic", "pulse", "time"}, new int[]{R.id.high_o, R.id.low_o, R.id.xinl_o, R.id.time_o});
            mlistview.setAdapter(adapter);

        }

        poastToast("数据同步成功");
    }

    public void poastToast(final String message) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT)
                        .show();
            }
        });
    }

    @Override
    public void onSuccess(Object arg0) {
        Log.v(TAG, "bond  onSuccess");
        poastToast("设备绑定成功");
    }

    @Override
    public void onProcess(int arg0) {

    }
    private void initView() {

        mToolbar = (Toolbar) this.findViewById(R.id.tool_bar11);
        //初始化ToolBar
        mToolbar.setTitle("");
        setSupportActionBar(mToolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeAsUpIndicator(R.drawable.icon_back);
        actionBar.setDisplayHomeAsUpEnabled(true);

        mData_systolic = (TextView) findViewById(R.id.high_o);
        mData_diastolic = (TextView) findViewById(R.id.low_o);
        mData_pulse = (TextView) findViewById(R.id.xinl_o);
        button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(this);

        button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(this);

        button3 = (Button) findViewById(R.id.button3);
        button3.setOnClickListener(this);

        mHandler = new Handler();

        // 获取manager
        oMRONDeviceManager = BPManager.getInstance(this);
        oMRONHealthDataManager = BPDataManager.getInstance(this);
        mlistview=(ListView)findViewById(R.id.list_o);


        Button button_upload=(Button)findViewById(R.id.button5);
        button_upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String tokenTest = UserInfos.token;
                Gson gson = new Gson();
                String dataString = gson.toJson(testlist).toString();
                HashMap<String, String> params = new HashMap<String, String>();
                params.put("token", tokenTest);
                params.put("json", dataString);
                PostStringRequest stringRequest = new PostStringRequest(Request.Method.POST, IpAddress.Upload_BloodPressure_Record, params,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                JSONObject json=null;
                                try {
                                    json = new JSONObject(response);
                                    boolean isFull = false;
                                    isFull = json.getBoolean("isFull");
                                    Intent intent = null;
                                    if (isFull) { // 上传成功
                                        // 更新血压信息
                                        LocalDataManager.getNetworkDataManager().getOneBloodPressureRecordByNetwork();
                                        LocalDataManager.getNetworkDataManager().getAllBloodPressreRecordByNetword();
                                        Toast.makeText(OmronHem.this, "上传血压数据成功！", Toast.LENGTH_SHORT).show();
                                    }
                                } catch (JSONException je) {
                                    je.printStackTrace();
                                }
                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError volleyError) {
                                Log.e("OmronHemError", volleyError.getMessage(), volleyError);
                                Toast.makeText(OmronHem.this, "上传血压数据失败！", Toast.LENGTH_SHORT).show();
                            }
                        });
                rQueue.add(stringRequest);
            }
        });
    }
}
